import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { API_BASE_URL } from '../../../../config/env'
import SimpleImage from '../../../components/common/SimpleImage'
import './product-detail.scss'

// 定义商品详情接口
interface ProductDetail {
  _id: string
  title: string
  price: number
  originalPrice: number
  saved: number
  hospital: string
  doctor: string
  rating: number
  description: string
  images: string[]
  features: string[]
  category: string
  tags: string[]
  // 虚拟数据字段
  experience: string
  hospitalAddress: string
  phone: string
  doctorAvatar: string
  treatmentTime: string
  recoveryTime: string
  precautions: string[]
  suitableFor: string[]
  contraindications: string[]
}

export default function ProductDetail() {
  const router = useRouter()
  const { id } = router.params
  const [product, setProduct] = useState<ProductDetail | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (id) {
      fetchProductData(id)
    } else {
      setLoading(false)
      Taro.showToast({
        title: '未找到商品信息',
        icon: 'error'
      })
    }
  }, [id])

  // 处理图片URL，将相对路径转换为完整URL
  const getFullImageUrl = (imageUrl) => {
    console.log('📦 商品详情页面原始图片URL:', imageUrl)
    console.log('🌐 API_BASE_URL:', API_BASE_URL)
    
    if (!imageUrl) {
      console.log('❌ 商品详情页面图片URL为空，使用备用图片')
      return 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=600&h=400&fit=crop'
    }
    
    // 处理完整URL，包括localhost替换
    if (imageUrl.startsWith('http')) {
      // 检查是否包含localhost，如果是则替换为API_BASE_URL
      if (imageUrl.includes('localhost') || imageUrl.includes('127.0.0.1')) {
        const path = imageUrl.replace(/^https?:\/\/[^\/]+/, '')
        const newUrl = `${API_BASE_URL}${path}`
        console.log('🔄 商品详情页面检测到localhost，替换为API_BASE_URL:', newUrl)
        return newUrl
      }
      console.log('✅ 商品详情页面检测到完整URL，直接使用:', imageUrl)
      return imageUrl
    }
    
    const fullUrl = imageUrl.startsWith('/') 
      ? `${API_BASE_URL}${imageUrl}`
      : `${API_BASE_URL}/${imageUrl}`
    
    console.log('🔗 商品详情页面拼接后的完整URL:', fullUrl)
    return fullUrl
  }

  // 获取商品数据
  const fetchProductData = async (productId: string) => {
    try {
      setLoading(true)
      console.log('开始获取商品数据，ID:', productId)
      
      const response = await Taro.request({
        url: `http://localhost:3000/cosmetic/products/${productId}`,
        method: 'GET',
        timeout: 10000
      })

      console.log('API响应:', response)

      if (response.statusCode === 200 && response.data && response.data.success) {
        const apiProduct = response.data.data
        console.log('获取到的商品数据:', apiProduct)
        
        // 补充虚拟数据
        const enhancedProduct: ProductDetail = {
          ...apiProduct,
          description: apiProduct.description || '这是一个专业的医疗美容项目，采用先进的技术和设备，由经验丰富的医生操作，确保安全有效。',
          images: apiProduct.images || [
            'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=600&h=400&fit=crop',
            'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=600&h=400&fit=crop',
            'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=600&h=400&fit=crop'
          ],
          features: apiProduct.features || [
            '专业医生操作',
            '安全无副作用',
            '效果显著持久',
            '个性化定制',
            '先进设备支持'
          ],
          tags: apiProduct.tags || ['热门', '推荐', '安全'],
          experience: '10年医美经验',
          hospitalAddress: '北京市朝阳区建国门外大街1号',
          phone: '400-123-4567',
          doctorAvatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=80&h=80&fit=crop&crop=face',
          treatmentTime: '30-60分钟',
          recoveryTime: '1-3天',
          precautions: [
            '术前24小时内避免饮酒',
            '术前12小时内避免进食',
            '术后注意防晒',
            '术后避免剧烈运动'
          ],
          suitableFor: [
            '想要改善皮肤问题的求美者',
            '希望提升面部轮廓的人群',
            '追求年轻化效果的用户'
          ],
          contraindications: [
            '孕妇及哺乳期妇女',
            '有严重心脏病史者',
            '对相关药物过敏者',
            '皮肤有炎症或感染者'
          ]
        }
        
        setProduct(enhancedProduct)
        console.log('商品详情数据:', enhancedProduct)
      } else {
        console.error('API响应格式错误:', response)
        throw new Error(`API响应错误: ${response.statusCode} - ${response.data?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('获取商品数据失败:', error)
      
      // 如果API调用失败，使用虚拟数据
      const mockProduct: ProductDetail = {
        _id: productId,
        title: '【抗衰套餐】半岛超声炮全面部+润致娃娃水光1次 面部紧致抗衰',
        price: 4085,
        originalPrice: 4299,
        saved: 214,
        hospital: '北京美莱医疗美容医院',
        doctor: '张医生',
        rating: 4.8,
        description: '半岛超声炮是一种非侵入性的紧肤治疗，通过超声波能量刺激胶原蛋白再生，达到紧致肌肤的效果。配合润致娃娃水光，能够深层补水，让肌肤更加水润有光泽。',
        images: [
          'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=600&h=400&fit=crop',
          'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=600&h=400&fit=crop',
          'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=600&h=400&fit=crop'
        ],
        features: [
          '非侵入性治疗',
          '刺激胶原蛋白再生',
          '深层补水保湿',
          '紧致肌肤效果',
          '安全无副作用'
        ],
        category: '抗衰',
        tags: ['热门', '推荐', '安全'],
        experience: '10年医美经验',
        hospitalAddress: '北京市朝阳区建国门外大街1号',
        phone: '400-123-4567',
        doctorAvatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=80&h=80&fit=crop&crop=face',
        treatmentTime: '30-60分钟',
        recoveryTime: '1-3天',
        precautions: [
          '术前24小时内避免饮酒',
          '术前12小时内避免进食',
          '术后注意防晒',
          '术后避免剧烈运动'
        ],
        suitableFor: [
          '想要改善皮肤问题的求美者',
          '希望提升面部轮廓的人群',
          '追求年轻化效果的用户'
        ],
        contraindications: [
          '孕妇及哺乳期妇女',
          '有严重心脏病史者',
          '对相关药物过敏者',
          '皮肤有炎症或感染者'
        ]
      }
      
      setProduct(mockProduct)
      Taro.showToast({
        title: '使用虚拟数据',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  // 预约咨询
  const handleConsultation = () => {
    if (!product) return
    
    // 使用医院信息作为咨询目标
    const hospitalId = product.hospitalId || product.hospital || ''
    const hospitalName = encodeURIComponent(product.hospital || '')
    const query = `?targetType=hospital&targetId=${hospitalId}&targetName=${hospitalName}`
    console.log('product consult -> navigateTo', `/pages/chat/chat${query}`)
    Taro.navigateTo({ url: `/pages/chat/chat${query}` })
      .catch(() => {
        Taro.showToast({
          title: '无法打开聊天页',
          icon: 'none'
        })
      })
  }

  // 立即购买
  const handleBuy = () => {
    Taro.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  }

  // 分享
  const handleShare = () => {
    Taro.showShareMenu({
      withShareTicket: true
    })
  }

  if (loading) {
    return (
      <View className='product-detail'>
        <View className='loading-container'>
          <Text>加载中...</Text>
        </View>
      </View>
    )
  }

  if (!product) {
    return (
      <View className='product-detail'>
        <View className='error-container'>
          <Text>商品信息不存在</Text>
        </View>
      </View>
    )
  }

  return (
    <View className='product-detail'>
      {/* 商品图片轮播 */}
      <ScrollView className='image-carousel' scrollX>
        {product.images.map((image, index) => (
          <SimpleImage 
            key={index} 
            src={image} 
            className='product-image' 
            mode='aspectFill'
            showLoadingSpinner={true}
          />
        ))}
      </ScrollView>

      {/* 商品基本信息 */}
      <View className='product-info'>
        <Text className='product-title'>{product.title}</Text>
        <View className='price-section'>
          <Text className='current-price'>¥{product.price}</Text>
          <Text className='original-price'>¥{product.originalPrice}</Text>
          <Text className='saved-price'>已省¥{product.saved}</Text>
        </View>
        <View className='rating-section'>
          <Text className='rating'>⭐ {product.rating ? product.rating.toFixed(1) : '0.0'}</Text>
          <Text className='hospital-name'>{product.hospital}</Text>
        </View>
        {product.tags && product.tags.length > 0 && (
          <View className='tags-section'>
            {product.tags.map((tag, index) => (
              <Text key={index} className='tag'>{tag}</Text>
            ))}
          </View>
        )}
      </View>

      {/* 医生信息 */}
      <View className='doctor-info'>
        <View className='doctor-header'>
          <Text className='doctor-title'>主治医生</Text>
        </View>
        <View className='doctor-detail'>
          <SimpleImage 
            src={product.doctorAvatar}
            className='doctor-avatar' 
            showLoadingSpinner={true}
          />
          <View className='doctor-text'>
            <Text className='doctor-name'>{product.doctor}</Text>
            <Text className='doctor-exp'>{product.experience}</Text>
          </View>
        </View>
      </View>

      {/* 治疗信息 */}
      <View className='treatment-info'>
        <View className='info-item'>
          <Text className='info-label'>治疗时间</Text>
          <Text className='info-value'>{product.treatmentTime}</Text>
        </View>
        <View className='info-item'>
          <Text className='info-label'>恢复时间</Text>
          <Text className='info-value'>{product.recoveryTime}</Text>
        </View>
      </View>

      {/* 商品详情 */}
      <View className='detail-section'>
        <Text className='section-title'>项目介绍</Text>
        <Text className='description'>{product.description}</Text>
      </View>

      {/* 项目特色 */}
      <View className='features-section'>
        <Text className='section-title'>项目特色</Text>
        <View className='features-list'>
          {product.features.map((feature, index) => (
            <View key={index} className='feature-item'>
              <Text className='feature-icon'>✓</Text>
              <Text className='feature-text'>{feature}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 适合人群 */}
      {product.suitableFor && product.suitableFor.length > 0 && (
        <View className='suitable-section'>
          <Text className='section-title'>适合人群</Text>
          <View className='suitable-list'>
            {product.suitableFor.map((item, index) => (
              <View key={index} className='suitable-item'>
                <Text className='suitable-icon'>👥</Text>
                <Text className='suitable-text'>{item}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* 注意事项 */}
      {product.precautions && product.precautions.length > 0 && (
        <View className='precautions-section'>
          <Text className='section-title'>注意事项</Text>
          <View className='precautions-list'>
            {product.precautions.map((item, index) => (
              <View key={index} className='precaution-item'>
                <Text className='precaution-icon'>⚠️</Text>
                <Text className='precaution-text'>{item}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* 禁忌症 */}
      {product.contraindications && product.contraindications.length > 0 && (
        <View className='contraindications-section'>
          <Text className='section-title'>禁忌症</Text>
          <View className='contraindications-list'>
            {product.contraindications.map((item, index) => (
              <View key={index} className='contraindication-item'>
                <Text className='contraindication-icon'>🚫</Text>
                <Text className='contraindication-text'>{item}</Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* 医院地址 */}
      <View className='hospital-section'>
        <Text className='section-title'>医院地址</Text>
        <Text className='hospital-address'>{product.hospitalAddress}</Text>
      </View>

      {/* 底部操作栏 */}
      <View className='bottom-actions'>
        <View className='action-left'>
          <View className='action-btn share-btn' onClick={handleShare}>
            <Text className='btn-icon'>📤</Text>
            <Text className='btn-text'>分享</Text>
          </View>
          <View className='action-btn consult-btn' onClick={handleConsultation}>
            <Text className='btn-icon'>💬</Text>
            <Text className='btn-text'>咨询</Text>
          </View>
        </View>
        <View className='buy-btn' onClick={handleBuy}>
          立即购买
        </View>
      </View>
    </View>
  )
}
